package features.advance.ch3;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class EchoServer implements Runnable{
    private static boolean done;

    public static void main(String[] args) {
//        if(args == null || args.length == 0){
//            System.out.println("请输入要下载的文件名");
//            return;
//        }
//        webServer(args[0]);
        webServer();
    }

    private static void webServer(){
        webServer(null);
    }

    private static void webServer(String arg) {

        try{
            OutputStream outStream = null;
            while(!done){

                String fileName = arg;
                ServerSocket s = new ServerSocket(8189,100, InetAddress.getByName("127.0.0.1"));
                Socket incoming = s.accept();
                int lc = 0;

                try{
                    InputStream inStream = incoming.getInputStream();
                    // 解析请求，封装HttpRequest对象
                    StringBuilder isb = new StringBuilder();
                    byte[] bytes = new byte[2048];
                    int inRead;
    //                while((inRead = inStream.read(bytes))!=-1){
    //                    isb.append(new String(bytes,0,inRead));
    //                }
                    System.out.println("请求报文："+isb.toString());
                    outStream = incoming.getOutputStream();
    //                Scanner scanner = new Scanner(inStream);
    //                PrintWriter out = new PrintWriter(outStream, true);
    //                out.println("Hello! Enter BYE to exit.");
                    StringBuilder sb = new StringBuilder();
                    if(fileName == null){
                        byte[] inData = new byte[2048];
                        int ir = -1;
                        while((ir=inStream.read(inData))!=-1){
                            String s1 = new String(inData, 0, ir);
                            System.out.println(s1);
                            String line1 = s1.split("\r")[0];
                            String s2 = line1.split(" ")[1];
                            System.out.println(s2);
                            fileName = s2;
                            if("/SHUTDOWN".equals(fileName)){
                                done = true;
                                break;
                            }
                            incoming.shutdownInput();
                        }

                    }
                    // 解密url中的中文
                    fileName = URLDecoder.decode(fileName,"UTF-8");
                    File file = new File(fileName);
                    if(!file.exists()){
                        String errorMessage = file.getAbsolutePath()+"不存在";
                        System.out.println(errorMessage);
//                        return;
                        StringBuffer err = new StringBuffer();
                        err.append("HTTP/1.1 404 OK\r\n");
                        String encodeFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");

                        err.append("Content-Type: application/json;charset=UTF-8\r\n");
                        //                sb.append("Content-Type: text/html;application/vnd.ms-excel\r\n");
                        err.append("Content-Length: "+errorMessage.length()+"\r\n");
                        outStream.write(err.toString().getBytes());
                        incoming.shutdownOutput();
                        outStream.close();
                        incoming.close();
                        s.close();
                        continue;
                    }
                    fileName = fileName.substring(fileName.lastIndexOf("/"));
                    sb.append("HTTP/1.1 200 OK\r\n");
                    String encodeFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
                    String format = String.format("attachment; filename=\"%s\"; filename*=%s''%s", encodeFileName, StandardCharsets.UTF_8.name(), encodeFileName);
                    sb.append("Content-Disposition: "+format+"\r\n");
                    sb.append("Content-Type: application/octet-stream;charset=UTF-8\r\n");
    //                sb.append("Content-Type: text/html;application/vnd.ms-excel\r\n");
                    sb.append("Content-Length: "+file.length()+"\r\n");
                    System.out.println(file.length());
                    // 注意这里要换行结束请求头
                    sb.append("\r\n");
                    outStream.write(sb.toString().getBytes());
                    try(FileInputStream fileInputStream = new FileInputStream(file);){
                        byte[] data = new byte[1024*1024];
                        int r = -1;
                        while((r=fileInputStream.read(data))!=-1){
                            outStream.write(data,0,r);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                    incoming.shutdownOutput();
                    System.out.println(lc);
                }catch (Exception e){
//                    e.printStackTrace();
                    if(outStream != null){
                        outStream.write(e.getMessage().getBytes());
                        outStream.flush();
                    }
                    incoming.close();
                }finally {
    //                Thread.sleep(6000L);
                    outStream.flush();
                    outStream.close();
                    s.close();
//                    incoming.close();
    //                s.close();

                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }



    public static void transition(String base64FileString,String outputFile){
        File file = new File(outputFile);
        try(FileOutputStream outputStream = new FileOutputStream(file)){
            outputStream.write(base64FileString.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static String downVersion(OutputStream os,String fileUrl){
        File file = new File(fileUrl);
        if(file.exists()){
            try(FileInputStream inputStream = new FileInputStream(file);){

            }catch (Exception e){
                e.printStackTrace();
            }

        }

        return null;
    }

    @Override
    public void run(){
        try {
            ServerSocket serverSocket = new ServerSocket(8190,1, InetAddress.getByName("127.0.0.1"));
            while(!done){
                Socket socket = null;
                socket = serverSocket.accept();


            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }


    }
}
